"""
traffic_platform.py - 交通突发事件综合处理平台

该文件包含交通事件处理平台的核心功能，包括:
1. 媒体数据处理
2. 红绿灯控制
3. AI模型集成
4. 综合事件处理流程
"""

import io
import json
import logging
import os
import pickle
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Union, Any, TypeVar, Generic
from event_database import event_db
import cv2
import numpy as np
import pandas as pd
import tensorflow as tf
from PIL import Image
from matplotlib import pyplot as plt
from tensorflow.keras.layers import (Input, Dense, LSTM, Conv2D, MaxPooling2D,
                                     Flatten, MultiHeadAttention, LayerNormalization)
from tensorflow.keras.models import Model
from transformers import TFBertModel

# 配置日志
logging.basicConfig(level=logging.INFO,
                   format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                   handlers=[
                       logging.FileHandler('traffic_platform.log'),
                       logging.StreamHandler()
                   ])
logger = logging.getLogger(__name__)

# 数据库目录配置
DATABASE_DIR = "D:\\ALOT数据库"
os.makedirs(DATABASE_DIR, exist_ok=True)

T = TypeVar('T')

class Singleton(type, Generic[T]):
    """单例模式元类"""
    _instances: Dict[type, T] = {}

    def __call__(cls, *args, **kwargs) -> T:
        """确保类只有一个实例"""
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class DatabaseManager:
    """数据库管理类，负责数据的存储和加载"""

    @staticmethod
    def save_data(data: Any, filename: str) -> None:
        """保存数据到文件"""
        filepath = os.path.join(DATABASE_DIR, filename)
        try:
            with open(filepath, 'wb') as f:
                pickle.dump(data, f)
            logger.info(f"数据已保存到 {filepath}")
        except Exception as e:
            logger.error(f"保存数据失败: {str(e)}")
    @staticmethod
    def load_data(filename: str) -> Any:
        """从文件加载数据"""
        filepath = os.path.join(DATABASE_DIR, filename)
        try:
            with open(filepath, 'rb') as f:
                return pickle.load(f)
        except FileNotFoundError:
            logger.warning(f"文件 {filepath} 不存在，返回空数据")
            return None
        except Exception as e:
            logger.error(f"加载数据失败: {str(e)}")
            return None


class ResultGenerator:
    """处理结果生成器，负责生成和输出AI处理后的结果"""

    @staticmethod
    def generate_result(platform: 'ComprehensiveTrafficPlatform', selected_options: List[Dict[str, Any]],
                        aggregated_data: pd.DataFrame, alert_level: Optional[int] = None) -> Dict[str, Any]:
        """
        生成处理结果报告

        参数:
            platform: 交通平台实例
            selected_options: 选中的处理选项
            aggregated_data: 聚合的事件数据
            alert_level: 警报级别

        返回:
            包含完整处理结果的字典
        """
        try:
            if aggregated_data.empty:
                logger.warning("无有效事件数据可用于生成结果")
                return {"error": "无有效事件数据", "status": "failed"}

            # 获取基本信息
            location = (aggregated_data["longitude"].iloc[0], aggregated_data["latitude"].iloc[0])
            event_type = aggregated_data["event_type"].iloc[0]

            # 构建结果字典
            result = {
                "event_id": len(platform.event_database),
                "timestamp": datetime.now().isoformat(),
                "location": {
                    "longitude": location[0],
                    "latitude": location[1],
                    "area_type": platform.determine_area_type(location)
                },
                "event_info": {
                    "type": event_type,
                    "confidence": float(aggregated_data["confidence"].mean()),
                    "severity": float(aggregated_data["severity"].mean()),
                    "scene_type": platform.scene_type,
                    "crowd_density": float(platform.crowd_density),
                    "has_injury": bool(aggregated_data["has_people"].any())
                },
                "alert_level": alert_level if alert_level is not None else 0,
                "processing_options": selected_options,
                "resource_allocation": [],
                "timeline": [
                    {"time": datetime.now().isoformat(), "action": "事件检测", "status": "完成"},
                    {"time": datetime.now().isoformat(), "action": "数据分析", "status": "完成"},
                    {"time": datetime.now().isoformat(), "action": "方案生成", "status": "完成"}
                ],
                "predicted_impact": {
                    "traffic_impact": min(1.0, aggregated_data["severity"].mean() * 0.8),
                    "duration": min(120, aggregated_data["severity"].mean() * 60)
                },
                "status": "success"
            }

            # 添加资源分配信息
            for option in selected_options:
                if option["key"] == "dynamic_resource_allocation":
                    result["resource_allocation"] = platform._simulate_resource_allocation(location, option["level"])
                    break
            return result
        except Exception as e:
            logger.error(f"生成结果时发生错误: {str(e)}")
            return {"error": f"生成结果错误: {str(e)}", "status": "failed"}


class MediaProcessor:
    """
    媒体数据处理类 - 负责图片和视频数据的分析处理
    """

    # 目标检测相关配置
    OBJECT_TYPES = ["vehicle", "person", "injured_person", "obstacle", "none"]
    OBJECT_PROBABILITIES = [0.3, 0.3, 0.1, 0.2, 0.1]  # 各类目标出现概率

    @staticmethod
    def process_image(image_data: Union[bytes, Image.Image]) -> Dict[str, Any]:
        """
        处理单张图片数据，提取事件相关特征

        参数:
            image_data: 图片数据，可以是bytes或PIL.Image对象

        返回:
            包含以下特征的字典:
            - image_size: 图片尺寸 (width, height)
            - detected_objects: 检测到的目标列表
            - crowd_density: 人群密度估计 (0.0-1.0)
            - scene_type: 场景类型分类
            - has_vehicle: 是否检测到车辆
            - has_injury: 是否检测到受伤人员
        """
        try:
            # 转换图像格式
            image = Image.open(io.BytesIO(image_data)) if isinstance(image_data, bytes) else image_data
            img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
            height, width = img_cv.shape[:2]

            # 检测目标
            detected_objects = MediaProcessor._detect_objects()

            return {
                "image_size": (width, height),
                "detected_objects": detected_objects,
                "crowd_density": MediaProcessor._estimate_crowd(detected_objects),
                "scene_type": MediaProcessor._classify_scene(detected_objects),
                "has_vehicle": any(obj["type"] == "vehicle" for obj in detected_objects),
                "has_injury": any(obj["type"] == "injured_person" for obj in detected_objects),
                "status": "success"
            }
        except Exception as e:
            logger.error(f"图片处理错误: {str(e)}")
            return {"error": f"Image processing error: {str(e)}", "status": "failed"}

    @staticmethod
    def process_video(video_data: Union[bytes, str], sample_interval: int = 5) -> Dict[str, Any]:
        """
        处理视频数据，提取关键帧和动态特征

        参数:
            video_data: 视频数据，可以是文件路径或bytes数据
            sample_interval: 采样间隔(秒)，默认为5秒

        返回:
            包含以下特征的字典:
            - duration: 视频时长(秒)
            - fps: 视频帧率
            - frame_count: 总帧数
            - key_frames: 关键帧分析结果列表
            - movement_analysis: 目标运动趋势分析
            - incident_spread: 事件影响范围扩散情况 (0.0-1.0)
        """
        cap = None
        temp_file = None

        try:
            # 处理bytes或文件路径的视频数据
            if isinstance(video_data, bytes):
                # 创建临时文件处理bytes视频数据
                import tempfile
                temp_file = tempfile.NamedTemporaryFile(suffix='.mp4')
                temp_file.write(video_data)
                temp_file.flush()
                cap = cv2.VideoCapture(temp_file.name)
            else:
                cap = cv2.VideoCapture(video_data)

            if not cap.isOpened():
                return {"error": "Failed to open video"}

            # 获取视频基本信息
            fps = cap.get(cv2.CAP_PROP_FPS)
            frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            duration = frame_count / fps if fps > 0 else 0

            key_frames = []
            frame_interval = int(fps * sample_interval) if fps > 0 else 1
            frame_idx = 0

            # 采样关键帧并分析
            while cap.isOpened():
                ret, frame = cap.read()
                if not ret:
                    break

                if frame_idx % frame_interval == 0:
                    try:
                        # 转换为PIL Image进行处理
                        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                        frame_img = Image.fromarray(frame_rgb)
                        frame_analysis = MediaProcessor.process_image(frame_img)
                        if "error" not in frame_analysis:
                            key_frames.append({
                                "timestamp": frame_idx / fps if fps > 0 else 0,
                                "frame_index": frame_idx,
                                "analysis": frame_analysis
                            })
                    except Exception as e:
                        logger.warning(f"处理帧 {frame_idx} 时出错: {str(e)}")

                frame_idx += 1

            if not key_frames:
                return {"error": "No valid frames processed"}

            # 综合分析结果
            object_movement = MediaProcessor._analyze_movement(key_frames)

            return {
                "duration": duration,
                "fps": fps,
                "frame_count": frame_count,
                "key_frames": key_frames,
                "movement_analysis": object_movement,
                "incident_spread": MediaProcessor._estimate_spread(key_frames)
            }

        except Exception as e:
            logger.error(f"视频处理错误: {str(e)}", exc_info=True)
            return {"error": f"Video processing error: {str(e)}"}
        finally:
            if cap is not None:
                cap.release()
            if temp_file is not None:
                temp_file.close()

    @staticmethod
    def _detect_objects() -> List[Dict[str, Any]]:
        """模拟目标检测 - 生成随机检测结果"""
        num_objects = np.random.randint(1, 6)  # 随机生成1-5个目标
        return [
            {
                "type": np.random.choice(MediaProcessor.OBJECT_TYPES, p=MediaProcessor.OBJECT_PROBABILITIES),
                "confidence": np.random.uniform(0.6, 0.99),
                "bbox": [
                    np.random.uniform(0, 0.8),
                    np.random.uniform(0, 0.8),
                    np.random.uniform(0.2, 1.0),
                    np.random.uniform(0.2, 1.0)
                ]
            }
            for _ in range(num_objects)
        ]

    @staticmethod
    def _estimate_crowd(objects: List[Dict[str, Any]]) -> float:
        """根据检测到的目标估计人群密度"""
        if not objects:
            return 0.0

        person_count = sum(1 for obj in objects if obj["type"] in ["person", "injured_person"])
        return min(1.0, person_count / 30)  # 使用更平滑的密度估计

    @staticmethod
    def _classify_scene(objects: List[Dict[str, Any]]) -> str:
        """根据检测到的目标分类场景类型"""
        if not objects:
            return "normal"

        has_vehicle = any(obj["type"] == "vehicle" for obj in objects)
        has_injury = any(obj["type"] == "injured_person" for obj in objects)
        has_obstacle = any(obj["type"] == "obstacle" for obj in objects)

        if has_injury:
            return "accident_with_injury"
        elif has_vehicle and len(objects) > 3:
            return "traffic_jam"
        elif has_obstacle:
            return "road_obstacle"
        return "normal"

    @staticmethod
    def _analyze_movement(key_frames: List[Dict[str, Any]]) -> str:
        """分析目标运动趋势"""
        if len(key_frames) < 2:
            return "insufficient_data"

        first_frame = key_frames[0]["analysis"]["detected_objects"]
        last_frame = key_frames[-1]["analysis"]["detected_objects"]

        first_count = sum(1 for obj in first_frame if obj["type"] == "vehicle")
        last_count = sum(1 for obj in last_frame if obj["type"] == "vehicle")

        if first_count == 0:
            return "stable" if last_count == 0 else "increasing_congestion"

        ratio = last_count / first_count

        if ratio > 1.5:
            return "increasing_congestion"
        elif ratio < 0.5:
            return "clearing_up"
        return "stable"

    @staticmethod
    def _estimate_spread(key_frames: List[Dict[str, Any]]) -> float:
        """估计事件影响范围扩散情况"""
        if len(key_frames) < 2:
            return 0.0

        def get_max_area(frame):
            """计算帧中最大目标的面积"""
            if not frame["analysis"]["detected_objects"]:
                return 0.0

            max_obj = max(frame["analysis"]["detected_objects"],
                          key=lambda x: (x["bbox"][2] - x["bbox"][0]) * (x["bbox"][3] - x["bbox"][1]),
                          default={"bbox": [0, 0, 0, 0]})
            return (max_obj["bbox"][2] - max_obj["bbox"][0]) * (max_obj["bbox"][3] - max_obj["bbox"][1])

        first_area = get_max_area(key_frames[0])
        last_area = get_max_area(key_frames[-1])

        if first_area <= 0:
            return 0.0

        return min(1.0, last_area / first_area)


class TrafficLightController:
    """
    红绿灯控制类 - 负责根据事件级别调整红绿灯配时
    """

    # 不同级别的基础延长秒数
    BASE_EXTENSIONS = {"high": 90, "medium": 60, "low": 30}
    # 不同级别影响的路口数量
    INTERSECTION_COUNTS = {"high": 5, "medium": 3, "low": 1}
    # 天气影响系数
    WEATHER_IMPACT = {
        "clear": 1.0,
        "rain": 1.2,
        "heavy_rain": 1.5,
        "fog": 1.3,
        "snow": 1.4
    }

    @staticmethod
    def adjust_light(location: Tuple[float, float], level: str, ext_data: Optional[Dict[str, Any]] = None) -> None:
        """
        调整红绿灯配时

        参数:
            location: 事件位置 (经度, 纬度)
            level: 事件级别 ("high", "medium", "low")
            ext_data: 外部数据，包含:
                - traffic_flow: 交通流量 (0.0-1.0)
                - weather: 天气类型
        """
        if level not in TrafficLightController.BASE_EXTENSIONS:
            raise ValueError(f"Invalid level: {level}")

        ext_data = ext_data or {}
        traffic_flow = ext_data.get('traffic_flow', 0.5)
        weather = ext_data.get('weather', 'clear')
        weather_impact = TrafficLightController.WEATHER_IMPACT.get(weather, 1.0)

        # 验证输入范围
        traffic_flow = max(0.0, min(1.0, traffic_flow))

        # 计算调整后的绿灯延长时间
        flow_factor = 1.0 + min(0.5, traffic_flow)
        adjusted_extension = int(TrafficLightController.BASE_EXTENSIONS[level] * flow_factor * weather_impact)

        # 记录调整信息
        logger.info(
            f"{level}级别红绿灯调整：{location}周边"
            f"{TrafficLightController.INTERSECTION_COUNTS[level]}个路口，"
            f"优先通行方向绿灯延长{adjusted_extension}秒 "
            f"(基于实时车流量: {traffic_flow:.2f}, 天气影响: {weather_impact:.1f})"
        )


class AIModels:
    """集成各类AI模型的容器类"""

    _instance = None  # 单例模式

    def __new__(cls):
        """实现单例模式"""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        """初始化AI模型"""
        self._models_loaded = False
        self.load_models()


    @staticmethod
    def _build_vad_model() -> Model:
        """构建声音活动检测模型"""
        inputs = Input(shape=(100, 64))  # 频谱特征
        x = LSTM(64, return_sequences=True)(inputs)
        x = LSTM(32)(x)
        outputs = Dense(1, activation='sigmoid')(x)  # 是否为有效声音

        model = Model(inputs=inputs, outputs=outputs)
        model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
        return model


    @staticmethod
    def _build_image_quality_model() -> Model:
        """构建图像质量评估模型"""
        inputs = Input(shape=(256, 256, 3))
        x = Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
        x = MaxPooling2D((2, 2))(x)
        x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
        x = MaxPooling2D((2, 2))(x)
        x = Flatten()(x)
        outputs = Dense(3, activation='sigmoid', name='quality_scores')(x)
        model = Model(inputs=inputs, outputs=outputs)
        model.compile(optimizer='adam', loss='mse')
        return model


    @staticmethod
    def _build_spatio_temporal_transformer() -> Model:
        """构建时空对齐Transformer模型"""
        inputs = Input(shape=(None, 4))  # [时间戳,经度,纬度,置信度]
        x = LayerNormalization()(inputs)
        x = MultiHeadAttention(num_heads=4, key_dim=64)(x, x)
        x = Dense(64, activation='relu')(x)
        outputs = Dense(4, name='aligned_output')(x)  # 对齐后的时空数据

        model = Model(inputs=inputs, outputs=outputs)
        model.compile(optimizer='adam', loss='mse')
        return model


    @staticmethod
    def _load_pretrained_bert() -> TFBertModel:
        """加载预训练的BERT模型用于事件分类"""
        try:
            logger.info("正在加载BERT模型...")
            model = TFBertModel.from_pretrained('bert-base-chinese')
            logger.info("BERT模型加载成功")
            return model
        except Exception as e:
            logger.error(f"加载BERT模型失败: {str(e)}")
            # 返回一个简单的后备模型
            inputs = Input(shape=(None,), dtype='int32')
            outputs = Dense(1)(inputs)
            return Model(inputs=inputs, outputs=outputs)

    @staticmethod
    def _build_rl_traffic_controller() -> Model:
        """构建强化学习交通控制器"""
        # 简化的策略网络
        inputs = Input(shape=(10,))  # 状态空间维度
        x = Dense(64, activation='relu')(inputs)
        x = Dense(32, activation='relu')(x)
        outputs = Dense(4, activation='softmax')(x)  # 4种交通控制动作

        model = Model(inputs=inputs, outputs=outputs)
        model.compile(optimizer='adam', loss='categorical_crossentropy')
        return model


    def load_models(self):
        """加载所有AI模型"""
        try:
            self.image_quality_model = self._build_image_quality_model()
            self.vad_model = self._build_vad_model()
            self.spatio_temporal_transformer = self._build_spatio_temporal_transformer()
            self.event_classifier = self._load_pretrained_bert()
            self.traffic_rl_agent = self._build_rl_traffic_controller()
            self._models_loaded = True
            logger.info("所有AI模型加载完成")
        except Exception as e:
            logger.error(f"加载AI模型失败: {str(e)}", exc_info=True)
            self._models_loaded = False

   


 

  
    def is_ready(self) -> bool:
        """检查所有模型是否已加载"""
        return self._models_loaded


class EnhancedMediaProcessor(MediaProcessor):
    """增强版媒体处理器，集成AI质量评估和特征提取"""

    def __init__(self):
        """初始化增强版媒体处理器"""
        super().__init__()
        self.ai_models = AIModels()

    def validate_image(self, image_data: Union[bytes, Image.Image]) -> Dict[str, Any]:
        """使用CNN评估图像质量"""
        try:
            # 转换和调整图像大小
            image = Image.open(io.BytesIO(image_data)) if isinstance(image_data, bytes) else image_data
            img = image.resize((256, 256))
            img_array = np.array(img) / 255.0

            # 处理不同图像格式
            if len(img_array.shape) == 2:  # 灰度图转RGB
                img_array = np.stack([img_array] * 3, axis=-1)
            elif img_array.shape[2] == 4:  # RGBA转RGB
                img_array = img_array[:, :, :3]

            # 预测质量
            scores = self.ai_models.image_quality_model.predict(np.expand_dims(img_array, axis=0))[0]

            return {
                'sharpness': float(scores[0]),
                'illumination': float(scores[1]),
                'has_road': float(scores[2] > 0.5),
                'is_valid': all(scores > 0.6),
                'status': 'success'  # 综合有效性判断
            }
        except Exception as e:
            logger.error(f"图像验证错误: {str(e)}")
            return {'error': f'Image validation error: {str(e)}', 'is_valid': False, 'status': 'failed'}

    def validate_audio(self, audio_data: bytes) -> Dict[str, Any]:
        """使用VAD模型验证音频有效性"""
        try:
            # 简化的频谱特征提取 (实际应使用librosa等库)
            spectrogram = np.random.rand(100, 64)  # 模拟频谱
            is_valid = self.ai_models.vad_model.predict(np.expand_dims(spectrogram, axis=0))[0][0] > 0.7

            return {
                'is_valid': bool(is_valid),
                'contains_crash': is_valid and np.random.rand() > 0.5  # 模拟碰撞检测
            }
        except Exception as e:
            logger.error(f"音频验证错误: {str(e)}")
            return {'error': f'Audio validation error: {str(e)}', 'is_valid': False}

    def process_image(self, image_data: Union[bytes, Image.Image]) -> Dict[str, Any]:
        """增强版图像处理，加入质量验证"""
        # 先验证图像质量
        validation = self.validate_image(image_data)
        if not validation.get('is_valid', False):
            return {'error': 'Invalid image', **validation}

        # 调用父类处理
        result = super().process_image(image_data)
        result['quality_validation'] = validation

        # 增强特征提取
        result['damage_estimate'] = self._estimate_damage(result)
        return result

    @staticmethod
    def _estimate_damage(analysis_result: Dict[str, Any]) -> Dict[str, Any]:
        """估计车辆损坏程度"""
        vehicles = [o for o in analysis_result['detected_objects'] if o['type'] == 'vehicle']
        vehicle_count = len(vehicles)

        if vehicle_count == 0:
            severity = 'none'
        elif vehicle_count == 1:
            severity = 'minor'
        elif vehicle_count == 2:
            severity = 'moderate'
        else:
            severity = 'severe'

        return {
            'vehicle_count': vehicle_count,
            'estimated_damage': min(1.0, vehicle_count * 0.2),
            'severity_category': severity
        }


class AlertSystem:
    """增强版警报系统，支持5级警报分类"""

    ALERT_LEVELS = {
        1: {'name': '观察', 'color': 'blue', 'response_time': 30},
        2: {'name': '轻微', 'color': 'green', 'response_time': 15},
        3: {'name': '中等', 'color': 'yellow', 'response_time': 10},
        4: {'name': '严重', 'color': 'orange', 'response_time': 5},
        5: {'name': '紧急', 'color': 'red', 'response_time': 1}
    }

    SPECIAL_AREAS = ['school', 'hospital', 'government']

    @classmethod
    def determine_alert_level(cls, severity: float, has_injury: bool,
                              area_type: str) -> int:
        """确定警报级别"""
        if severity <= 0:
            return 1

        base_level = min(5, max(1, int(severity * 5)))

        # 受伤人员提升级别
        if has_injury:
            base_level = min(5, base_level + 1)

        # 特殊区域提升级别
        if area_type in cls.SPECIAL_AREAS:
            base_level = min(5, base_level + 1)

        return base_level

    @classmethod
    def generate_alert_message(cls, level: int, event_data: Dict[str, Any]) -> str:
        """生成结构化警报消息"""
        if level not in cls.ALERT_LEVELS:
            return ""

        templates = {
            1: "观察到轻微交通异常于{location}，建议关注",
            2: "{location}发生轻微交通事件，类型：{event_type}",
            3: "{location}发生{event_type}，预计影响交通",
            4: "严重事件！{location}发生{event_type}，需立即响应",
            5: "紧急事件！{location}发生{event_type}，多人受伤，需立即处置"
        }

        return templates.get(level, "").format(
            location=event_data.get("location", "未知位置"),
            event_type=event_data.get("event_type", "未知事件")
        )


class ComprehensiveTrafficPlatform:
    """
    交通突发事件综合处理平台核心类
    """

    def __init__(self):
        """初始化平台组件和参数"""
        self.AREA_BOUNDARIES = None
        self.event_database = []  # 事件记录数据库
        self.traffic_light_controller = TrafficLightController()  # 红绿灯控制器
        self.media_processor = MediaProcessor()  # 媒体处理器

        # 事件特征状态
        self.scene_type = "unknown"  # 当前场景类型
        self.crowd_density = 0.0  # 人群密度 (0.0-1.0)
        self.incident_spread = 0.0  # 事件扩散程度 (0.0-1.0)

        # 处理选项配置
        self.processing_options = self._init_processing_options()
        # 选项评估模型
        self.option_evaluation_model = self.build_option_evaluation_model()

    @staticmethod
    def _init_processing_options() -> Dict[str, Any]:
        """初始化处理选项配置"""
        return {
            "record_event": {
                "name": "记录事件详情",
                "description": "将事件时间、位置、类型等信息存入数据库",
                "levels": {
                    "low": "仅记录基本信息（时间、位置、类型）",
                    "medium": "记录详细信息+关联设备数据",
                    "high": "记录完整信息+实时更新+多副本备份"
                }
            },
            "adjust_traffic_light": {
                "name": "红绿灯调整",
                "description": "根据事件影响范围动态调整红绿灯配时",
                "levels": {
                    "low": "轻微调整，影响范围1个路口",
                    "medium": "中度调整，影响范围3个路口",
                    "high": "深度调整，影响范围5个路口+优先通行方向"
                }
            },
            "notify_patrol": {
                "name": "通知巡逻车",
                "description": "派遣巡逻车前往现场",
                "levels": {
                    "low": "通知最近巡逻车关注",
                    "medium": "派遣1辆巡逻车前往",
                    "high": "派遣多辆巡逻车紧急前往"
                }
            },
            "notify_police": {
                "name": "通知交警部门",
                "description": "通知交通警察处理事件",
                "levels": {
                    "low": "记录事件并通知交警",
                    "medium": "要求交警前往处理",
                    "high": "要求交警紧急处置并上报"
                }
            },
            "notify_ambulance": {
                "name": "通知救护车",
                "description": "在有人员受伤时通知医疗救援",
                "levels": {
                    "low": "准备医疗支援",
                    "medium": "派遣1辆救护车",
                    "high": "派遣多辆救护车+医疗团队"
                }
            },
            "broadcast_alert": {
                "name": "发布广播提示",
                "description": "向周边车辆和行人发布警示信息",
                "levels": {
                    "low": "局部范围提示",
                    "medium": "中等范围警示",
                    "high": "大范围紧急广播"
                }
            },
            "special_traffic_control": {
                "name": "特殊交通管制",
                "description": "实施特殊交通管制措施",
                "levels": {
                    "low": "部分车道限流",
                    "medium": "单车道封闭",
                    "high": "多车道封闭或路段临时关闭"
                }
            },
            "multi_department_coordination": {
                "name": "多部门协调",
                "description": "协调多部门联合响应",
                "levels": {
                    "low": "通知相关责任部门",
                    "medium": "协调交警和相关关键部门",
                    "high": "启动多部门应急机制"
                }
            },
            "real_time_monitoring": {
                "name": "实时监控",
                "description": "加强对事件的实时监控",
                "levels": {
                    "low": "定期检查",
                    "medium": "加强监控频率",
                    "high": "专人值守+秒级更新"
                }
            }
        }

    def build_option_evaluation_model(self) -> Model:
        """构建处理选项评估模型"""
        input_layer = Input(shape=(8,), name="event_features")
        dense1 = Dense(32, activation="relu", name="hidden_layer1")(input_layer)
        dense2 = Dense(16, activation="relu", name="hidden_layer2")(dense1)

        # 必要性输出 (每个选项一个输出单元)
        necessity_output = Dense(
            len(self.processing_options),
            activation="sigmoid",
            name="necessity_output"
        )(dense2)

        # 级别输出 (每个选项一个输出单元，3个类别: low, medium, high)
        level_output = Dense(
            len(self.processing_options) * 3,  # 每个选项有3个级别
            activation="softmax",
            name="level_output"
        )(dense2)
        level_output = tf.reshape(level_output, (-1, len(self.processing_options), 3))

        model = Model(inputs=input_layer, outputs=[necessity_output, level_output])
        model.compile(
            optimizer="adam",
            loss={
                "necessity_output": "binary_crossentropy",
                "level_output": "sparse_categorical_crossentropy"
            },
            metrics={
                "necessity_output": "accuracy",
                "level_output": "accuracy"
            }
        )
        return model

    @staticmethod
    def get_confidence_level(confidence: float) -> str:
        """根据置信度分数获取置信级别"""
        if confidence < 0.5:
            return "low"
        elif confidence < 0.8:
            return "medium"
        return "high"

    def message_aggregation(self, device_reports_data: Dict[str, Any],
                            media_data_input: Optional[Dict[str, Any]] = None) -> pd.DataFrame:
        """聚合多设备上报的数据和媒体数据"""
        # 处理媒体数据
        media_analysis = self._process_media_data(media_data_input) if media_data_input else {}
        records = []

        for device_id, report in device_reports_data.items():
            if len(report) != 6:
                continue  # 跳过格式不正确的报告

            timestamp, location, confidence, event_type, severity, has_people = report

            # 验证位置数据
            if not isinstance(location, (tuple, list)) or len(location) != 2:
                continue

            # 创建记录
            records.append({
                "time": datetime.fromtimestamp(timestamp),
                "longitude": float(location[0]),
                "latitude": float(location[1]),
                "confidence": float(confidence),
                "event_type": str(event_type),
                "device_id": str(device_id),
                "severity": self._adjust_severity(float(severity), media_analysis),
                "area_type": self.determine_area_type(location),
                "has_people": bool(has_people) or media_analysis.get("has_injury", False),
                "media_analysis": media_analysis
            })

        return pd.DataFrame(records) if records else pd.DataFrame()

    def _process_media_data(self, media_data_input: Dict[str, Any]) -> Dict[str, Any]:
        """处理媒体数据并整合分析结果"""
        # 处理所有图片和视频
        image_results = []
        for img in media_data_input.get("images", []):
            result = self.media_processor.process_image(img)
            if "error" not in result:
                image_results.append(result)

        video_results = []
        for vid in media_data_input.get("videos", []):
            result = self.media_processor.process_video(vid)
            if "error" not in result:
                video_results.append(result)

        # 聚合结果
        return self._aggregate_media_results(image_results, video_results)

    @staticmethod
    def _aggregate_media_results(image_results: List[Dict[str, Any]],
                                 video_results: List[Dict[str, Any]]) -> Dict[str, Any]:
        """聚合所有媒体分析结果"""
        if not image_results and not video_results:
            return {}

        # 从图片结果中提取特征
        image_features = {
            "has_injury": [img.get("has_injury", False) for img in image_results],
            "crowd_density": [img.get("crowd_density", 0) for img in image_results],
            "scene_type": [img.get("scene_type") for img in image_results if img.get("scene_type")]
        }

        # 从视频结果中提取特征
        video_features = {
            "has_injury": [
                frame["analysis"].get("has_injury", False)
                for vid in video_results
                for frame in vid.get("key_frames", [])
            ],
            "crowd_density": [
                frame["analysis"].get("crowd_density", 0)
                for vid in video_results
                for frame in vid.get("key_frames", [])
            ],
            "scene_type": [
                frame["analysis"].get("scene_type")
                for vid in video_results
                for frame in vid.get("key_frames", [])
                if frame["analysis"].get("scene_type")
            ],
            "incident_spread": [vid.get("incident_spread", 0) for vid in video_results]
        }

        # 合并特征
        has_injury = any(image_features["has_injury"]) or any(video_features["has_injury"])
        crowd_density = max(
            max(image_features["crowd_density"], default=0),
            max(video_features["crowd_density"], default=0)
        )
        scene_types = image_features["scene_type"] + video_features["scene_type"]
        dominant_scene = max(set(scene_types), key=scene_types.count) if scene_types else "unknown"

        return {
            "has_injury": has_injury,
            "crowd_density": crowd_density,
            "dominant_scene": dominant_scene,
            "image_count": len(image_results),
            "video_count": len(video_results),
            "incident_spread": max(video_features["incident_spread"], default=0)
        }

    @staticmethod
    def _adjust_severity(original_severity: float, media_analysis: Dict[str, Any]) -> float:
        """根据媒体分析结果调整事件严重程度"""
        if not media_analysis:
            return original_severity

        # 基础调整
        adjusted = original_severity

        # 如果有人员受伤，严重程度至少为中等
        if media_analysis.get("has_injury", False):
            adjusted = max(adjusted, 0.6)

        # 人群密度和事件扩散影响
        adjusted += media_analysis.get("crowd_density", 0) * 0.3
        adjusted += media_analysis.get("incident_spread", 0) * 0.2

        return min(1.0, max(0.0, adjusted))  # 确保在0-1范围内

    def determine_area_type(self, location: Tuple[float, float]) -> str:
        """根据位置确定区域类型"""
        if not location or len(location) != 2:
            return "normal"

        longitude, latitude = location

        # 检查是否在特殊区域内
        for area_type, ((lon_min, lon_max), (lat_min, lat_max)) in self.AREA_BOUNDARIES.items():
            if lon_min <= longitude <= lon_max and lat_min <= latitude <= lat_max:
                return area_type
        return "normal"

    def event_fusion(self, aggregated_data: pd.DataFrame) -> Tuple[bool, float, float, str, bool]:
        """融合分析所有事件数据"""
        if aggregated_data.empty:
            return False, 0.0, 0.0, "normal", False

        # 计算平均指标
        avg_confidence = aggregated_data["confidence"].mean()
        avg_severity = aggregated_data["severity"].mean()
        area_type = aggregated_data["area_type"].mode()[0] if not aggregated_data["area_type"].empty else "normal"
        has_people = aggregated_data["has_people"].any()

        # 从媒体分析中获取额外信息
        media_analysis = aggregated_data["media_analysis"].iloc[0] if not aggregated_data.empty else {}
        self.scene_type = media_analysis.get("dominant_scene", "unknown")
        self.crowd_density = media_analysis.get("crowd_density", 0.0)
        self.incident_spread = media_analysis.get("incident_spread", 0.0)

        return avg_confidence > 0.7, avg_confidence, avg_severity, area_type, has_people

    def select_options(self, confidence: float, severity: float,
                       area_type: str, has_people: bool) -> List[Dict[str, Any]]:
        """根据事件特征选择处理选项"""
        # 获取交通流量估计
        traffic_flow = self.get_traffic_flow(area_type)
        # 是否为特殊区域
        is_special_area = 1 if area_type in self.AREA_BOUNDARIES else 0

        # 构建模型输入特征
        features = np.array([[
            confidence,
            severity,
            is_special_area,
            traffic_flow,
            1 if has_people else 0,
            self.crowd_density,
            1 if self.scene_type == "accident_with_injury" else 0,
            self.incident_spread
        ]])

        # 模型预测
        try:
            necessity_scores, level_scores = self.option_evaluation_model.predict(features, verbose=0)
            necessity_scores = necessity_scores[0]
            level_predictions = np.argmax(level_scores[0], axis=1)
        except Exception as e:
            logger.error(f"选项评估模型失败: {str(e)}")
            return []

        base_level = self.get_confidence_level(confidence)
        level_priority = {"low": 0, "medium": 1, "high": 2}
        selected_options = []

        # 选择必要性大于0.5的选项
        for idx, (opt_key, opt_info) in enumerate(self.processing_options.items()):
            if idx >= len(necessity_scores):
                continue

            if necessity_scores[idx] > 0.5:
                predicted_level = {0: "low", 1: "medium", 2: "high"}[level_predictions[idx]]

                # 确保预测级别不低于基础级别
                final_level = (predicted_level
                               if level_priority[predicted_level] >= level_priority[base_level]
                               else base_level)

                selected_options.append({
                    "key": opt_key,
                    "name": opt_info["name"],
                    "necessity": float(necessity_scores[idx]),
                    "level": final_level,
                    "level_desc": opt_info["levels"][final_level],
                    "traffic_flow": traffic_flow
                })

        # 按必要性降序排序
        return sorted(selected_options, key=lambda x: x["necessity"], reverse=True)

    @staticmethod
    def get_traffic_flow(area_type: str) -> float:
        """获取区域交通流量估计"""
        traffic_flows = {
            "school": 0.8,
            "hospital": 0.6,
            "government": 0.5
        }
        return traffic_flows.get(area_type, 0.3 + np.random.random() * 0.4)

    def execute_options(self, selected_options: List[Dict[str, Any]], location: Tuple[float, float],
                        event_type: str, confidence: float, ext_data: Optional[Dict[str, Any]] = None) -> None:
        """执行选定的处理选项"""
        ext_data = ext_data or {}
        logger.info("\n===== 处理方案 =====")
        logger.info(f"事件位置：{location}")
        logger.info(f"事件类型：{event_type}")
        logger.info(f"事件可信度：{confidence:.2f}（{self.get_confidence_level(confidence)}级别）")
        logger.info(f"选中的处理选项（共{len(selected_options)}项）：")

        # 执行每个选项
        for option in selected_options:
            logger.info(f"- {option['name']}（必要性：{option['necessity']:.2f}，处理级别：{option['level']}）")
            logger.info(f"  处理内容：{option['level_desc']}")
            self.execute_option_action(option, location, ext_data)

    def execute_option_action(self, option: Dict[str, Any], location: Tuple[float, float],
                              ext_data: Dict[str, Any]) -> None:
        """执行单个处理选项"""
        # 选项处理器映射
        action_handlers = {
            "record_event": lambda: self.record_event(location, option["level"]),
            "adjust_traffic_light": lambda: self._handle_traffic_light_adjustment(option, location, ext_data),
            "notify_patrol": lambda: self.notify_authorities(location, "巡逻车", option["level"]),
            "notify_police": lambda: self.notify_authorities(location, "交警部门", option["level"]),
            "notify_ambulance": lambda: self.notify_authorities(location, "救护车", option["level"]),
            "broadcast_alert": lambda: self.broadcast_alert(location, option["level"]),
            "special_traffic_control": lambda: self.special_traffic_control(location, option["level"]),
            "multi_department_coordination": lambda: self.coordinate_departments(location, option["level"]),
            "real_time_monitoring": lambda: self.monitor_event(location, option["level"])
        }

        # 执行对应的处理器
        handler = action_handlers.get(option["key"])
        if handler:
            try:
                handler()
            except Exception as e:
                logger.error(f"执行选项 {option['name']} 时出错: {str(e)}")

    def _handle_traffic_light_adjustment(self, option: Dict[str, Any], location: Tuple[float, float],
                                         ext_data: Dict[str, Any]) -> None:
        """处理红绿灯调整"""
        traffic_data = {
            'traffic_flow': option['traffic_flow'],
            'weather_impact': ext_data.get('weather_impact', 1.0)
        }
        self.traffic_light_controller.adjust_light(location, option["level"], traffic_data)

    def record_event(self, location: Tuple[float, float], level: str) -> None:
        """记录事件到数据库"""
        # 不同级别的记录详情
        details_map = {
            "high": ("完整事件信息+多设备数据+实时更新标记", "已备份（多副本）"),
            "medium": ("详细事件信息+关联设备数据", "未备份"),
            "low": ("基本事件信息（时间、位置、类型）", "未备份")
        }

        details, backup_status = details_map.get(level, ("", "未备份"))

        # 添加到数据库
        self.event_database.append({
            "location": location,
            "record_time": datetime.now(),
            "level": level,
            "details": details,
            "backup_status": backup_status
        })
        logger.info(f"事件已记录（ID: {len(self.event_database) - 1}）")

    @staticmethod
    def notify_authorities(location: Tuple[float, float], authority_type: str, level: str) -> None:
        """通知相关部门"""
        priority = {
            "high": "紧急优先级",
            "medium": "常规优先级",
            "low": "非紧急"
        }.get(level, "非紧急")
        logger.info(f"已向{authority_type}发送通知（{priority}）：位置{location}发生事件")

    @staticmethod
    def broadcast_alert(location: Tuple[float, float], level: str) -> None:
        """发布广播提示"""
        alert_config = {
            "high": ("5公里范围", "紧急事件，请立即绕行"),
            "medium": ("3公里范围", "发生事件，建议绕行"),
            "low": ("1公里范围", "前方有事件，请减速慢行")
        }
        range_desc, content = alert_config.get(level, ("1公里范围", "前方有事件，请减速慢行"))
        logger.info(f"在{range_desc}内发布广播：{content}（位置：{location}）")

    @staticmethod
    def special_traffic_control(location: Tuple[float, float], level: str) -> None:
        """实施特殊交通管制"""
        measures = {
            "high": "多车道封闭或路段临时关闭",
            "medium": "单车道封闭",
            "low": "部分车道限流"
        }
        logger.info(f"在{location}实施交通管制：{measures.get(level, '部分车道限流')}")

    @staticmethod
    def coordinate_departments(location: Tuple[float, float], level: str) -> None:
        """协调多部门响应"""
        departments = {
            "high": "交警、消防、医疗等多个部门（启动应急机制）",
            "medium": "交警和相关关键部门",
            "low": "相关责任部门"
        }
        logger.info(f"协调{departments.get(level, '相关责任部门')}处理{location}的事件")

    @staticmethod
    def monitor_event(location: Tuple[float, float], level: str) -> None:
        """实时监控事件"""
        frequencies = {
            "high": "秒级更新+专人值守",
            "medium": "1分钟/次",
            "low": "5分钟/次"
        }
        logger.info(f"对{location}的事件进行监控，更新频率：{frequencies.get(level, '5分钟/次')}")

    def process_events(self, device_reports_data: Dict[str, Any],
                       media_data_input: Optional[Dict[str, Any]] = None,
                       ext_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """完整事件处理流程"""
        try:
            aggregated_data = self.message_aggregation(device_reports_data, media_data_input)

            if aggregated_data.empty:
                return {"status": "no_valid_events"}
            location = (aggregated_data["longitude"].iloc[0], aggregated_data["latitude"].iloc[0])
            event_type = aggregated_data["event_type"].iloc[0]
            if isinstance(self, EnhancedComprehensiveTrafficPlatform):
                is_high_conf, confidence, severity, area_type, has_people, alert_level = self.event_fusion(
                    aggregated_data)
            else:
                is_high_conf, confidence, severity, area_type, has_people = self.event_fusion(aggregated_data)
                alert_level = None

            selected_options = self.select_options(confidence, severity, area_type, has_people)
            self.execute_options(selected_options, location, event_type, confidence, ext_data)

            return ResultGenerator.generate_result(self, selected_options, aggregated_data, alert_level)
        except Exception as e:
            logger.error(f"处理事件时发生错误: {str(e)}", exc_info=True)
            return {"error": f"处理事件错误: {str(e)}", "status": "failed"}



class EnhancedComprehensiveTrafficPlatform(ComprehensiveTrafficPlatform):
    """增强版综合交通处理平台"""

    def __init__(self):
        """初始化增强版平台"""
        super().__init__()
        self.media_processor = EnhancedMediaProcessor()
        self.alert_system = AlertSystem()
        self.ai_models = AIModels()

        # 增强处理选项
        self.processing_options.update({
            "dynamic_resource_allocation": {
                "name": "动态资源分配",
                "description": "基于强化学习的应急资源动态调度",
                "levels": {
                    "low": "分配基础资源包",
                    "medium": "分配标准资源包+1辆巡逻车",
                    "high": "分配高级资源包+多部门联合响应"
                }
            },
            "ai_visual_report": {
                "name": "AI可视化报告",
                "description": "生成包含时序分析和预测的可视化报告",
                "levels": {
                    "low": "基础事件时间线",
                    "medium": "带影响范围预测的2D可视化",
                    "high": "3D场景重建+多视角模拟"
                }
            }
        })

    def message_aggregation(self, device_reports_data: Dict[str, Any],
                            media_data_input: Optional[Dict[str, Any]] = None) -> pd.DataFrame:
        """增强版数据聚合，加入时空对齐"""
        # 时空对齐处理
        aligned_reports = self._align_spatio_temporal_data(device_reports_data)

        # 处理媒体数据
        media_analysis = self._process_media_data(media_data_input) if media_data_input else {}

        records = []
        for device_id, report in aligned_reports.items():
            if len(report) != 6:
                continue

            timestamp, location, confidence, event_type, severity, has_people = report

            records.append({
                "time": datetime.fromtimestamp(timestamp),
                "longitude": location[0],
                "latitude": location[1],
                "confidence": confidence,
                "event_type": self._standardize_event_type(event_type),
                "device_id": device_id,
                "severity": self._adjust_severity(severity, media_analysis),
                "area_type": self.determine_area_type(location),
                "has_people": has_people or media_analysis.get("has_injury", False),
                "media_analysis": media_analysis,
                "aligned": True  # 标记已对齐
            })

        return pd.DataFrame(records) if records else pd.DataFrame()

    def _align_spatio_temporal_data(self, raw_reports: Dict[str, Any]) -> Dict[str, Any]:
        """使用时序Transformer对齐多源时空数据"""
        if not raw_reports:
            return {}

        # 准备输入数据 [时间戳,经度,纬度,置信度]
        input_data = []
        for report in raw_reports.values():
            if len(report) != 6:
                continue
            timestamp, loc, conf = report[0], report[1], report[2]
            input_data.append([timestamp, loc[0], loc[1], conf])

        if not input_data:
            return raw_reports

        try:
            # 对齐处理 (简化版，实际应使用完整模型)
            aligned = self.ai_models.spatio_temporal_transformer.predict(np.array([input_data]))[0]

            # 更新报告数据
            aligned_reports = {}
            for i, (device_id, report) in enumerate(raw_reports.items()):
                if i < len(aligned):
                    new_time = aligned[i][0]
                    new_loc = (aligned[i][1], aligned[i][2])
                    new_conf = aligned[i][3]
                    aligned_reports[device_id] = (new_time, new_loc, new_conf, *report[3:])
                else:
                    aligned_reports[device_id] = report

            return aligned_reports
        except Exception as e:
            logger.error(f"时空对齐失败: {str(e)}")
            return raw_reports

    @staticmethod
    def _standardize_event_type(raw_type: str) -> str:
        """标准化事件类型描述"""
        type_mapping = {
            "撞车": "车辆碰撞",
            "碰撞": "车辆碰撞",
            "追尾": "车辆追尾",
            "翻车": "车辆翻覆",
            "急刹": "紧急制动"
        }
        return type_mapping.get(raw_type, raw_type)

    def event_fusion(self, aggregated_data: pd.DataFrame) -> Tuple[bool, float, float, str, bool, int]:
        """增强版事件融合，加入警报级别计算"""
        base_result = super().event_fusion(aggregated_data)
        is_high_conf, confidence, severity, area_type, has_people = base_result

        # 计算警报级别
        alert_level = self.alert_system.determine_alert_level(severity, has_people, area_type)

        # 生成警报消息
        if not aggregated_data.empty:
            event_data = {
                "location": f"({aggregated_data['longitude'].iloc[0]:.4f}, "
                            f"{aggregated_data['latitude'].iloc[0]:.4f})",
                "event_type": aggregated_data["event_type"].iloc[0]
            }
            alert_message = self.alert_system.generate_alert_message(alert_level, event_data)
            logger.info(f"警报级别 {alert_level}: {alert_message}")

        return (*base_result, alert_level)

    def select_options(self, confidence: float, severity: float,
                       area_type: str, has_people: bool) -> List[Dict[str, Any]]:
        """增强版选项选择，加入RL资源分配"""
        base_options = super().select_options(confidence, severity, area_type, has_people)

        # 添加动态资源分配选项
        if severity > 0.5:
            base_options.append({
                "key": "dynamic_resource_allocation",
                "name": "动态资源分配",
                "necessity": min(1.0, severity * 1.2),
                "level": "high" if severity > 0.8 else "medium",
                "level_desc": self.processing_options["dynamic_resource_allocation"][
                    "levels"]["high" if severity > 0.8 else "medium"],
                "traffic_flow": self.get_traffic_flow(area_type)
            })

        # 添加AI可视化报告选项
        if has_people or severity > 0.7:
            base_options.append({
                "key": "ai_visual_report",
                "name": "AI可视化报告",
                "necessity": 0.7 if has_people else 0.5,
                "level": "high" if has_people else "medium",
                "level_desc": self.processing_options["ai_visual_report"][
                    "levels"]["high" if has_people else "medium"],
                "traffic_flow": self.get_traffic_flow(area_type)
            })

        return sorted(base_options, key=lambda x: x["necessity"], reverse=True)

    def execute_option_action(self, option: Dict[str, Any], location: Tuple[float, float],
                              ext_data: Dict[str, Any]) -> None:
        """增强版选项执行，支持新增选项"""
        # 新增选项处理器
        enhanced_handlers = {
            "dynamic_resource_allocation": lambda: self.allocate_resources(location, option["level"]),
            "ai_visual_report": lambda: self.generate_visual_report(location, option["level"])
        }

        # 尝试执行增强处理器
        handler = enhanced_handlers.get(option["key"])
        if handler:
            try:
                handler()
            except Exception as e:
                logger.error(f"执行增强选项 {option['name']} 时出错: {str(e)}")
        else:
            # 回退到基础处理器
            super().execute_option_action(option, location, ext_data)

    def allocate_resources(self, location: Tuple[float, float], level: str) -> None:
        """基于强化学习的资源分配"""
        try:
            # 获取当前状态
            state = self._get_rl_state(location)

            # 获取RL模型决策
            action_probs = self.ai_models.traffic_rl_agent.predict(np.array([state]))[0]
            action = np.argmax(action_probs)

            resources = {
                0: ["基础医疗包", "1辆巡逻车"],
                1: ["高级医疗包", "2辆巡逻车", "消防单元"],
                2: ["全套应急资源", "多部门联合响应"],
                3: ["特种救援设备", "直升机支援"]
            }.get(action, ["基础医疗包"])

            logger.info(f"资源分配决策（RL策略{action}）：{', '.join(resources)}")
        except Exception as e:
            logger.error(f"资源分配失败: {str(e)}")

    def _get_rl_state(self, location: Tuple[float, float]) -> List[float]:
        """获取RL模型所需状态向量"""
        return [
            self.crowd_density,
            self.incident_spread,
            1 if self.scene_type == "accident_with_injury" else 0,
            self.get_traffic_flow(self.determine_area_type(location)),
            *location,
            datetime.now().hour / 24,  # 标准化时间
            min(1.0, len(self.event_database) / 100)  # 事件活跃度
        ]

    @staticmethod
    def generate_visual_report(location: Tuple[float, float], level: str) -> None:
        """生成AI可视化报告"""
        techniques = {
            "low": "生成基础时间线图",
            "medium": "生成2D热力图和影响范围预测",
            "high": "生成3D场景重建和多方视角模拟"
        }
        logger.info(f"正在{techniques.get(level, '生成报告')}...")
        logger.info("AI可视化报告已生成并发送至指挥中心")

def save_visualization(self, result: Dict[str, Any],
                       filename: str = None, VISUALIZATION_DIR=None) -> bool:
    """保存可视化结果到文件

    参数:
        result: 处理结果字典
        filename: 保存文件名，默认为'result_visualization.png'

    返回:
        保存是否成功
    """
    fig = self.visualize_result(result)
    if fig is None:
        return False

    if filename is None:
        filename = f"result_visualization_{result.get('event_id', 'unknown')}.png"

    filepath = os.path.join(VISUALIZATION_DIR, filename)

    try:
        fig.savefig(filepath, dpi=300, bbox_inches='tight')  
        plt.close(fig)
        return True
    except Exception as e:
        print(f"保存可视化结果失败: {str(e)}")
        return False
    
# 示例用法
if __name__ == "__main__":
    platform = EnhancedComprehensiveTrafficPlatform()
    device_reports = {
        "cam-001": (1625097600, (116.305, 39.905), 0.85, "撞车", 0.7, True),
        "cam-002": (1625097601, (116.3051, 39.9051), 0.75, "碰撞", 0.6, True)
    }
    media_data = {
        "images": [Image.new('RGB', (640, 480), color='red')],
        "videos": [io.BytesIO(b"simulated_video_data")]
    }
    ext_data = {"weather": "rain", "traffic_flow": 0.8}
    result = platform.process_events(device_reports, media_data, ext_data)
    print(json.dumps(result, indent=2, ensure_ascii=False))



